package com.yunhe.day322.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunhe.day322.dao.RoleDao;
import com.yunhe.day322.domain.Permission;
import com.yunhe.day322.domain.Role;
import com.yunhe.day322.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    /**
     * 查询所有
     * @param page
     * @param size
     * @param model
     * @return
     */
    @RequestMapping("findAll")
    public String findAll(@RequestParam(value = "page", defaultValue = "1") Integer page ,
                          @RequestParam(value = "size",defaultValue = "5") Integer size,
                          Model model){

        PageHelper.startPage(page,size);
        List<Role> list = roleService.findAll(page,size);

        PageInfo pageInfo = new PageInfo(list);
        model.addAttribute("pageInfo",pageInfo);

        return "role-list";
    }
    /**
     * 新增角色
     * @param role
     * @return
     */
    @RequestMapping("save")
    public String save(Role role){
        roleService.save(role);
        return "redirect:findAll";
    }
    /**
     * 角色详情
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("findById")
    public String findById(int id,Model model){
         Role role = roleService.findById(id);
         model.addAttribute("role",role);
         return "role-show";
    }
    @RequestMapping("findRoleByIdAndAllPermission")
    public String findRoleByIdAndPer(int id,Model model){
       //查询当前的角色是谁
        Role role = roleService.findById(id);
        model.addAttribute("role",role);
       //查询当前角色的那些权限可以添加
        List<Permission> list = roleService.findOtherPermission(id);
        model.addAttribute("permissionList",list);

        return "role-permission-add";
    }
    //给角色添加权限
    @RequestMapping("addPermissionToRole")
    public String addPermissionToRole(int roleId,int[] ids){
        roleService.addPermissionToRole(roleId,ids);
        return "redirect:findAll";
    }
    /**
     * 删除角色
     * @param id
     * @return
     */
    @RequestMapping("deleteRole")
    public String deleteRole(int id){
        roleService.deleteRole(id);
        return "redirect:findAll";
    }
}
